<template>
  <div class="app-page">
    <table-search
      label-width="80px"
      :search-form="searchFormItem"
      :on-submit="handleQuery"
      :on-reset="handleQuery"
    />
    <el-card>
      <div class="content">
        <div class="app-table-action-wrap">
          <auth-button
            auth-key="b_2_1"
            type="primary"
            icon="el-icon-plus"
            size="small"
            @click="handleAdd"
          >
            新增
          </auth-button>
        </div>

        <table-paging
          :table-list="tableList"
          :table-column="tableColumn"
          :table-btn-width="200"
          :table-paging="tablePaging"
          :table-total="tableTotal"
          @pagingChange="handlePaginChange"
        />

        <dialog-form
          ref="dialogForm"
          width="400px"
          :title="dialogTitle"
          :visible="dialogVisible"
          :before-close="() => (dialogVisible = false)"
          :form-attrs="{formData: modalFormData, renderFormItem, formButtons, rules, labelWidth: '130px'}"
        />

        <properties ref="properties" :visible.sync="propertiesVisible" />
      </div>
    </el-card>
  </div>
</template>

<script>
import { fetchComponentTypeFindPage, fetchComponentTypeGet, fetchComponentTypeDelete, fetchComponentTypeAdd, fetchComponentTypeUpdate, fetchComponentTypeUpdateStatus } from '@/api/basicinfo/parts/type'

import { TableSearch, TablePaging, DialogForm, AuthButton } from '@/components'
import Properties from './properties'
import { searchFormItem, tableColumn, renderFormItem, formButtons, formRules } from './config'

export default {
  name: 'Type',
  components: { TableSearch, TablePaging, DialogForm, Properties, AuthButton },
  data() {
    return {
      searchFormData: {}, // 查询数据
      searchFormItem, // 查询 form 配置

      tableList: [], // table数据
      tableColumn: tableColumn(this.handleEdit, this.handleUpdateStatus, this.handleConfig, this.handleDelete), // tableColumn 配置
      tableTotal: 0,
      tablePaging: {
        page: 1,
        pagesize: 10
      },

      dialogTitle: '新增', // 弹窗标题
      dialogVisible: false, // 弹窗显示隐藏
      modalFormData: {}, // 弹窗表单数据
      deviceCodeDisabled: false, // 设备号是否禁止修改

      renderFormItem: [],
      formButtons: formButtons(this.handleModalSubmit, this.hanleClose),
      rules: formRules,

      propertiesVisible: false
    }
  },
  created() {
    this.postFindPage()
  },
  methods: {
    handleQuery(values) { // 查询
      this.searchFormData = values
      this.tablePaging = {
        page: 1,
        pagesize: 10
      }
      this.postFindPage()
    },

    handleMarkChange(e) { // 位置标注方式变化
      if (e !== 1) {
        delete this.modalFormData.icon
      }
      this._createRenderFormItem(e !== 1, this.modalFormData.id)
    },

    handleAdd() { // 添加
      this._setModalData()
      this._createRenderFormItem()
      this.dialogVisible = true
    },

    handleEdit(id) { // 修改
      this.postGet(id)
    },

    handleUpdateStatus(id, status) { // 更新状态
      this.postStatusUpdate(id, status)
    },

    handleConfig(id) { // 配置
      this.propertiesVisible = true
      this.$refs.properties.componentTypeId = id
      this.$refs.properties.postFindPage(id)
    },

    handleDelete(id) { // 删除
      this.postDelete(id)
    },

    handleModalSubmit(values) { // 弹窗提交
      if (this._checkFormData(values)) {
        if (values.id) {
          this.postUpdate(values)
          return false
        }
        this.postAdd(values)
      }
    },

    hanleClose() {
      this.dialogVisible = false
    },

    handlePaginChange(pageInfo) { // 分页改变
      this.tablePaging = pageInfo
      this.postFindPage()
    },

    handleBeforeUpload(file) { // 图片验证
      const isPng = file.type === 'image/png'
      if (!isPng) {
        this.$message.warning('部件图标只能是PNG格式!')
        return false
      }
      return true
    },

    handleExceed() { // 图片验证
      this.$message.warning('只能上传一张图片, 如需更换先删除!')
      return false
    },

    handleUploadSuccess(url) { // 图片上传成功回调
      this.$refs.dialogForm.$refs.modalForm.setFormData({ icon: url })
      this.modalFormData.icon = url
    },

    _createRenderFormItem(isHide = true, rowId = 0, file = []) { // 创建  modal formitem
      this.renderFormItem = renderFormItem(this.handleMarkChange, isHide, this.handleBeforeUpload, this.handleUploadSuccess, this.handleExceed, rowId, file)
    },

    _checkFormData(data) { // 验证是否上传
      if (data.markType === 1) {
        if (!data.icon) {
          this.$message.warning('请上传部件图标!')
          return false
        }
        return true
      }
      return true
    },

    _setModalData(title = '新增', visible = true, modalFormData = {}) { // 设置弹窗
      this.modalFormData = modalFormData
      this.dialogTitle = title
      this.dialogVisible = visible
    },

    postFindPage() { // 查询数据
      fetchComponentTypeFindPage({ ...this.searchFormData, ...this.tablePaging })
        .then((res) => {
          const { records, current, size, total } = res
          this.tableList = records
          this.tablePaging = {
            page: current,
            pagesize: size
          }
          this.tableTotal = total
        })
    },

    postAdd(values) { // 添加
      fetchComponentTypeAdd(values).then(res => {
        this.dialogVisible = false
        this.$message.success('新增成功')
        this.postFindPage()
      })
    },

    postGet(id) { // 获取详情
      fetchComponentTypeGet({ id }).then(res => {
        if (res.icon) {
          this._createRenderFormItem(false, res.id, [{ name: '', url: res.icon }])
        } else {
          this._createRenderFormItem(true, res.id)
        }
        this._setModalData('修改', true, res)
      })
    },

    postDelete(id) { // 删除
      fetchComponentTypeDelete({ id }).then(() => {
        this.$message.success('删除成功')
        this.postFindPage()
      })
    },

    postUpdate(values) { // 更新
      fetchComponentTypeUpdate(values).then(() => {
        this.dialogVisible = false
        this.$message.success('修改成功')
        this.postFindPage()
      })
    },

    postStatusUpdate(id, enabled) { // 更新状态
      fetchComponentTypeUpdateStatus({ id, enabled }).then(() => {
        this.$message.success('开启成功!')
        this.postFindPage()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.app-page {
  .upload-demo .el-upload--picture-card {
    width: 40px;
    height: 40px;
  }
}
</style>
